3 * This is the MS SQL Server Native database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Joel Penner <a-joelpe at microsoft dot com>
23 * @author Chris Pucci <a-cpucci at microsoft dot com>
24 * @author Ryan Biesemeyer <v-ryanbi at microsoft dot com>
25 * @author Ryan Schmidt <skizzerz at gmail dot com>
28 namespace Wikimedia\Rdbms
;
37 class DatabaseMssql
extends Database
{
39 protected $serverPort;
41 protected $useWindowsAuth = false;
43 protected $lastInsertId = null;
45 protected $lastAffectedRowCount = null;
47 protected $subqueryId = 0;
49 protected $scrollableCursor = true;
51 protected $prepareStatements = true;
52 /** @var stdClass[][]|null */
53 protected $binaryColumnCache = null;
54 /** @var stdClass[][]|null */
55 protected $bitColumnCache = null;
57 protected $ignoreDupKeyErrors = false;
59 protected $ignoreErrors = [];
61 public function implicitGroupby() {
65 public function implicitOrderby() {
69 public function unionSupportsOrderAndLimit() {
73 public function __construct( array $params ) {
74 $this->serverPort
= $params['port'];
75 $this->useWindowsAuth
= $params['UseWindowsAuth'];
77 parent
::__construct( $params );
80 protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix ) {
81 # Test for driver support, to avoid suppressed fatal error
82 if ( !function_exists( 'sqlsrv_connect' ) ) {
83 throw new DBConnectionError(
85 "Microsoft SQL Server Native (sqlsrv) functions missing.
86 You can download the driver from: http://go.microsoft.com/fwlink/?LinkId=123470\n"
90 # e.g. the class is being loaded
91 if ( !strlen( $user ) ) {
96 $this->server
= $server;
98 $this->password
= $password;
100 $connectionInfo = [];
102 if ( $dbName != '' ) {
103 $connectionInfo['Database'] = $dbName;
106 // Decide which auth scenerio to use
107 // if we are using Windows auth, then don't add credentials to $connectionInfo
108 if ( !$this->useWindowsAuth
) {
109 $connectionInfo['UID'] = $user;
110 $connectionInfo['PWD'] = $password;
113 Wikimedia\
suppressWarnings();
114 $this->conn
= sqlsrv_connect( $server, $connectionInfo );
115 Wikimedia\restoreWarnings
();
117 if ( $this->conn
=== false ) {
118 throw new DBConnectionError( $this, $this->lastError() );
121 $this->opened
= true;
122 $this->currentDomain
= new DatabaseDomain(
123 ( $dbName != '' ) ?
$dbName : null,
128 return (bool)$this->conn
;
132 * Closes a database connection, if it is open
133 * Returns success, true if already closed
136 protected function closeConnection() {
137 return sqlsrv_close( $this->conn
);
141 * @param bool|MssqlResultWrapper|resource $result
142 * @return bool|MssqlResultWrapper
144 protected function resultObject( $result ) {
147 } elseif ( $result instanceof MssqlResultWrapper
) {
149 } elseif ( $result === true ) {
150 // Successful write query
153 return new MssqlResultWrapper( $this, $result );
159 * @return bool|MssqlResultWrapper|resource
160 * @throws DBUnexpectedError
162 protected function doQuery( $sql ) {
163 // several extensions seem to think that all databases support limits
164 // via LIMIT N after the WHERE clause, but MSSQL uses SELECT TOP N,
165 // so to catch any of those extensions we'll do a quick check for a
166 // LIMIT clause and pass $sql through $this->LimitToTopN() which parses
167 // the LIMIT clause and passes the result to $this->limitResult();
168 if ( preg_match( '/\bLIMIT\s*/i', $sql ) ) {
169 // massage LIMIT -> TopN
170 $sql = $this->LimitToTopN( $sql );
173 // MSSQL doesn't have EXTRACT(epoch FROM XXX)
174 if ( preg_match( '#\bEXTRACT\s*?\(\s*?EPOCH\s+FROM\b#i', $sql, $matches ) ) {
175 // This is same as UNIX_TIMESTAMP, we need to calc # of seconds from 1970
176 $sql = str_replace( $matches[0], "DATEDIFF(s,CONVERT(datetime,'1/1/1970'),", $sql );
181 // SQLSRV_CURSOR_STATIC is slower than SQLSRV_CURSOR_CLIENT_BUFFERED (one of the two is
182 // needed if we want to be able to seek around the result set), however CLIENT_BUFFERED
183 // has a bug in the sqlsrv driver where wchar_t types (such as nvarchar) that are empty
184 // strings make php throw a fatal error "Severe error translating Unicode"
185 if ( $this->scrollableCursor
) {
186 $scrollArr = [ 'Scrollable' => SQLSRV_CURSOR_STATIC
];
191 if ( $this->prepareStatements
) {
192 // we do prepare + execute so we can get its field metadata for later usage if desired
193 $stmt = sqlsrv_prepare( $this->conn
, $sql, [], $scrollArr );
194 $success = sqlsrv_execute( $stmt );
196 $stmt = sqlsrv_query( $this->conn
, $sql, [], $scrollArr );
197 $success = (bool)$stmt;
200 // Make a copy to ensure what we add below does not get reflected in future queries
201 $ignoreErrors = $this->ignoreErrors
;
203 if ( $this->ignoreDupKeyErrors
) {
204 // ignore duplicate key errors
205 // this emulates INSERT IGNORE in MySQL
206 $ignoreErrors[] = '2601'; // duplicate key error caused by unique index
207 $ignoreErrors[] = '2627'; // duplicate key error caused by primary key
208 $ignoreErrors[] = '3621'; // generic "the statement has been terminated" error
211 if ( $success === false ) {
212 $errors = sqlsrv_errors();
215 foreach ( $errors as $err ) {
216 if ( !in_array( $err['code'], $ignoreErrors ) ) {
222 if ( $success === false ) {
226 // remember number of rows affected
227 $this->lastAffectedRowCount
= sqlsrv_rows_affected( $stmt );
232 public function freeResult( $res ) {
233 if ( $res instanceof ResultWrapper
) {
237 sqlsrv_free_stmt( $res );
241 * @param IResultWrapper $res
244 public function fetchObject( $res ) {
245 // $res is expected to be an instance of MssqlResultWrapper here
246 return $res->fetchObject();
250 * @param IResultWrapper $res
253 public function fetchRow( $res ) {
254 return $res->fetchRow();
261 public function numRows( $res ) {
262 if ( $res instanceof ResultWrapper
) {
266 $ret = sqlsrv_num_rows( $res );
268 if ( $ret === false ) {
269 // we cannot get an amount of rows from this cursor type
270 // has_rows returns bool true/false if the result has rows
271 $ret = (int)sqlsrv_has_rows( $res );
281 public function numFields( $res ) {
282 if ( $res instanceof ResultWrapper
) {
286 return sqlsrv_num_fields( $res );
294 public function fieldName( $res, $n ) {
295 if ( $res instanceof ResultWrapper
) {
299 return sqlsrv_field_metadata( $res )[$n]['Name'];
303 * This must be called after nextSequenceVal
306 public function insertId() {
307 return $this->lastInsertId
;
311 * @param MssqlResultWrapper $res
315 public function dataSeek( $res, $row ) {
316 return $res->seek( $row );
322 public function lastError() {
324 $retErrors = sqlsrv_errors( SQLSRV_ERR_ALL
);
325 if ( $retErrors != null ) {
326 foreach ( $retErrors as $arrError ) {
327 $strRet .= $this->formatError( $arrError ) . "\n";
330 $strRet = "No errors found";
340 private function formatError( $err ) {
341 return '[SQLSTATE ' .
342 $err['SQLSTATE'] . '][Error Code ' . $err['code'] . ']' . $err['message'];
348 public function lastErrno() {
349 $err = sqlsrv_errors( SQLSRV_ERR_ALL
);
350 if ( $err !== null && isset( $err[0] ) ) {
351 return $err[0]['code'];
357 protected function wasKnownStatementRollbackError() {
358 $errors = sqlsrv_errors( SQLSRV_ERR_ALL
);
362 // The transaction vs statement rollback behavior depends on XACT_ABORT, so make sure
363 // that the "statement has been terminated" error (3621) is specifically present.
364 // https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql
365 $statementOnly = false;
366 $codeWhitelist = [ '2601', '2627', '547' ];
367 foreach ( $errors as $error ) {
368 if ( $error['code'] == '3621' ) {
369 $statementOnly = true;
370 } elseif ( !in_array( $error['code'], $codeWhitelist ) ) {
371 $statementOnly = false;
376 return $statementOnly;
382 protected function fetchAffectedRowCount() {
383 return $this->lastAffectedRowCount
;
389 * @param mixed $table Array or string, table name(s) (prefix auto-added)
390 * @param mixed $vars Array or string, field name(s) to be retrieved
391 * @param mixed $conds Array or string, condition(s) for WHERE
392 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
393 * @param array $options Associative array of options (e.g.
394 * [ 'GROUP BY' => 'page_title' ]), see Database::makeSelectOptions
395 * code for list of supported stuff
396 * @param array $join_conds Associative array of table join conditions
397 * (optional) (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
398 * @return mixed Database result resource (feed to Database::fetchObject
399 * or whatever), or false on failure
400 * @throws DBQueryError
401 * @throws DBUnexpectedError
404 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
405 $options = [], $join_conds = []
407 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
408 if ( isset( $options['EXPLAIN'] ) ) {
410 $this->scrollableCursor
= false;
411 $this->prepareStatements
= false;
412 $this->query( "SET SHOWPLAN_ALL ON" );
413 $ret = $this->query( $sql, $fname );
414 $this->query( "SET SHOWPLAN_ALL OFF" );
415 } catch ( DBQueryError
$dqe ) {
416 if ( isset( $options['FOR COUNT'] ) ) {
417 // likely don't have privs for SHOWPLAN, so run a select count instead
418 $this->query( "SET SHOWPLAN_ALL OFF" );
419 unset( $options['EXPLAIN'] );
420 $ret = $this->select(
422 'COUNT(*) AS EstimateRows',
429 // someone actually wanted the query plan instead of an est row count
430 // let them know of the error
431 $this->scrollableCursor
= true;
432 $this->prepareStatements
= true;
436 $this->scrollableCursor
= true;
437 $this->prepareStatements
= true;
440 return $this->query( $sql, $fname );
446 * @param mixed $table Array or string, table name(s) (prefix auto-added)
447 * @param mixed $vars Array or string, field name(s) to be retrieved
448 * @param mixed $conds Array or string, condition(s) for WHERE
449 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
450 * @param array $options Associative array of options (e.g. [ 'GROUP BY' => 'page_title' ]),
451 * see Database::makeSelectOptions code for list of supported stuff
452 * @param array $join_conds Associative array of table join conditions (optional)
453 * (e.g. [ 'page' => [ 'LEFT JOIN','page_latest=rev_id' ] ]
454 * @return string The SQL text
456 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
457 $options = [], $join_conds = []
459 if ( isset( $options['EXPLAIN'] ) ) {
460 unset( $options['EXPLAIN'] );
463 $sql = parent
::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
465 // try to rewrite aggregations of bit columns (currently MAX and MIN)
466 if ( strpos( $sql, 'MAX(' ) !== false ||
strpos( $sql, 'MIN(' ) !== false ) {
468 if ( is_array( $table ) ) {
471 $t = array_pop( $tables );
472 if ( is_array( $t ) ) {
473 $tables = array_merge( $tables, $t );
475 $bitColumns +
= $this->getBitColumns( $this->tableName( $t ) );
479 $bitColumns = $this->getBitColumns( $this->tableName( $table ) );
482 foreach ( $bitColumns as $col => $info ) {
484 "MAX({$col})" => "MAX(CAST({$col} AS tinyint))",
485 "MIN({$col})" => "MIN(CAST({$col} AS tinyint))",
487 $sql = str_replace( array_keys( $replace ), array_values( $replace ), $sql );
494 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
497 $this->scrollableCursor
= false;
499 parent
::deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname );
500 } catch ( Exception
$e ) {
501 $this->scrollableCursor
= true;
504 $this->scrollableCursor
= true;
507 public function delete( $table, $conds, $fname = __METHOD__
) {
508 $this->scrollableCursor
= false;
510 parent
::delete( $table, $conds, $fname );
511 } catch ( Exception
$e ) {
512 $this->scrollableCursor
= true;
515 $this->scrollableCursor
= true;
521 * Estimate rows in dataset
522 * Returns estimated count, based on SHOWPLAN_ALL output
523 * This is not necessarily an accurate estimate, so use sparingly
524 * Returns -1 if count cannot be found
525 * Takes same arguments as Database::select()
526 * @param string $table
528 * @param string $conds
529 * @param string $fname
530 * @param array $options
531 * @param array $join_conds
534 public function estimateRowCount( $table, $var = '*', $conds = '',
535 $fname = __METHOD__
, $options = [], $join_conds = []
537 $conds = $this->normalizeConditions( $conds, $fname );
538 $column = $this->extractSingleFieldFromList( $var );
539 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
540 $conds[] = "$column IS NOT NULL";
543 // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
544 $options['EXPLAIN'] = true;
545 $options['FOR COUNT'] = true;
546 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
550 $row = $this->fetchRow( $res );
552 if ( isset( $row['EstimateRows'] ) ) {
553 $rows = (int)$row['EstimateRows'];
561 * Returns information about an index
562 * If errors are explicitly ignored, returns NULL on failure
563 * @param string $table
564 * @param string $index
565 * @param string $fname
566 * @return array|bool|null
568 public function indexInfo( $table, $index, $fname = __METHOD__
) {
569 # This does not return the same info as MYSQL would, but that's OK
570 # because MediaWiki never uses the returned value except to check for
571 # the existence of indexes.
572 $sql = "sp_helpindex '" . $this->tableName( $table ) . "'";
573 $res = $this->query( $sql, $fname );
580 foreach ( $res as $row ) {
581 if ( $row->index_name
== $index ) {
582 $row->Non_unique
= !stristr( $row->index_description
, "unique" );
583 $cols = explode( ", ", $row->index_keys
);
584 foreach ( $cols as $col ) {
585 $row->Column_name
= trim( $col );
586 $result[] = clone $row;
588 } elseif ( $index == 'PRIMARY' && stristr( $row->index_description
, 'PRIMARY' ) ) {
589 $row->Non_unique
= 0;
590 $cols = explode( ", ", $row->index_keys
);
591 foreach ( $cols as $col ) {
592 $row->Column_name
= trim( $col );
593 $result[] = clone $row;
598 return $result ?
: false;
602 * INSERT wrapper, inserts an array into a table
604 * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
607 * Usually aborts on failure
608 * If errors are explicitly ignored, returns success
609 * @param string $table
610 * @param array $arrToInsert
611 * @param string $fname
612 * @param array $options
616 public function insert( $table, $arrToInsert, $fname = __METHOD__
, $options = [] ) {
617 # No rows to insert, easy just return now
618 if ( !count( $arrToInsert ) ) {
622 if ( !is_array( $options ) ) {
623 $options = [ $options ];
626 $table = $this->tableName( $table );
628 if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
629 $arrToInsert = [ 0 => $arrToInsert ]; // make everything multi row compatible
632 // We know the table we're inserting into, get its identity column
634 // strip matching square brackets and the db/schema from table name
635 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
636 $tableRaw = array_pop( $tableRawArr );
637 $res = $this->doQuery(
638 "SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS " .
639 "WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'"
641 if ( $res && sqlsrv_has_rows( $res ) ) {
642 // There is an identity for this table.
643 $identityArr = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC
);
644 $identity = array_pop( $identityArr );
646 sqlsrv_free_stmt( $res );
648 // Determine binary/varbinary fields so we can encode data as a hex string like 0xABCDEF
649 $binaryColumns = $this->getBinaryColumns( $table );
651 // INSERT IGNORE is not supported by SQL Server
652 // remove IGNORE from options list and set ignore flag to true
653 if ( in_array( 'IGNORE', $options ) ) {
654 $options = array_diff( $options, [ 'IGNORE' ] );
655 $this->ignoreDupKeyErrors
= true;
659 foreach ( $arrToInsert as $a ) {
660 // start out with empty identity column, this is so we can return
661 // it as a result of the INSERT logic
664 $identityClause = '';
666 // if we have an identity column
669 foreach ( $a as $k => $v ) {
670 if ( $k == $identity ) {
671 if ( !is_null( $v ) ) {
672 // there is a value being passed to us,
673 // we need to turn on and off inserted identity
674 $sqlPre = "SET IDENTITY_INSERT $table ON;";
675 $sqlPost = ";SET IDENTITY_INSERT $table OFF;";
677 // we can't insert NULL into an identity column,
678 // so remove the column from the insert.
684 // we want to output an identity column as result
685 $identityClause = "OUTPUT INSERTED.$identity ";
688 $keys = array_keys( $a );
690 // Build the actual query
691 $sql = $sqlPre . 'INSERT ' . implode( ' ', $options ) .
692 " INTO $table (" . implode( ',', $keys ) . ") $identityClause VALUES (";
695 foreach ( $a as $key => $value ) {
696 if ( isset( $binaryColumns[$key] ) ) {
697 $value = new MssqlBlob( $value );
704 if ( is_null( $value ) ) {
706 } elseif ( is_array( $value ) ||
is_object( $value ) ) {
707 if ( is_object( $value ) && $value instanceof Blob
) {
708 $sql .= $this->addQuotes( $value );
710 $sql .= $this->addQuotes( serialize( $value ) );
713 $sql .= $this->addQuotes( $value );
716 $sql .= ')' . $sqlPost;
719 $this->scrollableCursor
= false;
721 $ret = $this->query( $sql );
722 } catch ( Exception
$e ) {
723 $this->scrollableCursor
= true;
724 $this->ignoreDupKeyErrors
= false;
727 $this->scrollableCursor
= true;
729 if ( $ret instanceof ResultWrapper
&& !is_null( $identity ) ) {
730 // Then we want to get the identity column value we were assigned and save it off
731 $row = $ret->fetchObject();
732 if ( is_object( $row ) ) {
733 $this->lastInsertId
= $row->$identity;
734 // It seems that mAffectedRows is -1 sometimes when OUTPUT INSERTED.identity is
735 // used if we got an identity back, we know for sure a row was affected, so
737 if ( $this->lastAffectedRowCount
== -1 ) {
738 $this->lastAffectedRowCount
= 1;
744 $this->ignoreDupKeyErrors
= false;
750 * INSERT SELECT wrapper
751 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
752 * Source items may be literals rather than field names, but strings should
753 * be quoted with Database::addQuotes().
754 * @param string $destTable
755 * @param array|string $srcTable May be an array of tables.
756 * @param array $varMap
757 * @param array $conds May be "*" to copy the whole table.
758 * @param string $fname
759 * @param array $insertOptions
760 * @param array $selectOptions
761 * @param array $selectJoinConds
764 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
765 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
767 $this->scrollableCursor
= false;
769 parent
::nativeInsertSelect(
779 } catch ( Exception
$e ) {
780 $this->scrollableCursor
= true;
783 $this->scrollableCursor
= true;
787 * UPDATE wrapper. Takes a condition array and a SET array.
789 * @param string $table Name of the table to UPDATE. This will be passed through
790 * Database::tableName().
792 * @param array $values An array of values to SET. For each array element,
793 * the key gives the field name, and the value gives the data
794 * to set that field to. The data will be quoted by
795 * Database::addQuotes().
797 * @param array $conds An array of conditions (WHERE). See
798 * Database::select() for the details of the format of
799 * condition arrays. Use '*' to update all rows.
801 * @param string $fname The function name of the caller (from __METHOD__),
802 * for logging and profiling.
804 * @param array $options An array of UPDATE options, can be:
805 * - IGNORE: Ignore unique key conflicts
806 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
808 * @throws DBUnexpectedError
811 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
812 $table = $this->tableName( $table );
813 $binaryColumns = $this->getBinaryColumns( $table );
815 $opts = $this->makeUpdateOptions( $options );
816 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
, $binaryColumns );
818 if ( $conds !== [] && $conds !== '*' ) {
819 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
, $binaryColumns );
822 $this->scrollableCursor
= false;
824 $this->query( $sql );
825 } catch ( Exception
$e ) {
826 $this->scrollableCursor
= true;
829 $this->scrollableCursor
= true;
834 * Makes an encoded list of strings from an array
835 * @param array $a Containing the data
836 * @param int $mode Constant
837 * - LIST_COMMA: comma separated, no field names
838 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
839 * the documentation for $conds in Database::select().
840 * - LIST_OR: ORed WHERE clause (without the WHERE)
841 * - LIST_SET: comma separated with field names, like a SET clause
842 * - LIST_NAMES: comma separated field names
843 * @param array $binaryColumns Contains a list of column names that are binary types
844 * This is a custom parameter only present for MS SQL.
846 * @throws DBUnexpectedError
849 public function makeList( $a, $mode = LIST_COMMA
, $binaryColumns = [] ) {
850 if ( !is_array( $a ) ) {
851 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
854 if ( $mode != LIST_NAMES
) {
855 // In MS SQL, values need to be specially encoded when they are
856 // inserted into binary fields. Perform this necessary encoding
857 // for the specified set of columns.
858 foreach ( array_keys( $a ) as $field ) {
859 if ( !isset( $binaryColumns[$field] ) ) {
863 if ( is_array( $a[$field] ) ) {
864 foreach ( $a[$field] as &$v ) {
865 $v = new MssqlBlob( $v );
869 $a[$field] = new MssqlBlob( $a[$field] );
874 return parent
::makeList( $a, $mode );
878 * @param string $table
879 * @param string $field
880 * @return int Returns the size of a text field, or -1 for "unlimited"
882 public function textFieldSize( $table, $field ) {
883 $table = $this->tableName( $table );
884 $sql = "SELECT CHARACTER_MAXIMUM_LENGTH,DATA_TYPE FROM INFORMATION_SCHEMA.Columns
885 WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'";
886 $res = $this->query( $sql );
887 $row = $this->fetchRow( $res );
889 if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
890 $size = $row['CHARACTER_MAXIMUM_LENGTH'];
897 * Construct a LIMIT query with optional offset
898 * This is used for query pages
900 * @param string $sql SQL query we will append the limit too
901 * @param int $limit The SQL limit
902 * @param bool|int $offset The SQL offset (default false)
903 * @return array|string
904 * @throws DBUnexpectedError
906 public function limitResult( $sql, $limit, $offset = false ) {
907 if ( $offset === false ||
$offset == 0 ) {
908 if ( strpos( $sql, "SELECT" ) === false ) {
909 return "TOP {$limit} " . $sql;
911 return preg_replace( '/\bSELECT(\s+DISTINCT)?\b/Dsi',
912 'SELECT$1 TOP ' . $limit, $sql, 1 );
915 // This one is fun, we need to pull out the select list as well as any ORDER BY clause
916 $select = $orderby = [];
917 $s1 = preg_match( '#SELECT\s+(.+?)\s+FROM#Dis', $sql, $select );
918 $s2 = preg_match( '#(ORDER BY\s+.+?)(\s*FOR XML .*)?$#Dis', $sql, $orderby );
920 $first = $offset +
1;
921 $last = $offset +
$limit;
922 $sub1 = 'sub_' . $this->subqueryId
;
923 $sub2 = 'sub_' . ( $this->subqueryId +
1 );
924 $this->subqueryId +
= 2;
927 throw new DBUnexpectedError( $this, "Attempting to LIMIT a non-SELECT query\n" );
931 $overOrder = 'ORDER BY (SELECT 1)';
933 if ( !isset( $orderby[2] ) ||
!$orderby[2] ) {
934 // don't need to strip it out if we're using a FOR XML clause
935 $sql = str_replace( $orderby[1], '', $sql );
937 $overOrder = $orderby[1];
938 $postOrder = ' ' . $overOrder;
940 $sql = "SELECT {$select[1]}
942 SELECT ROW_NUMBER() OVER({$overOrder}) AS rowNumber, *
943 FROM ({$sql}) {$sub1}
945 WHERE rowNumber BETWEEN {$first} AND {$last}{$postOrder}";
952 * If there is a limit clause, parse it, strip it, and pass the remaining
953 * SQL through limitResult() with the appropriate parameters. Not the
954 * prettiest solution, but better than building a whole new parser. This
955 * exists becase there are still too many extensions that don't use dynamic
959 * @return array|mixed|string
961 public function LimitToTopN( $sql ) {
962 // Matches: LIMIT {[offset,] row_count | row_count OFFSET offset}
963 $pattern = '/\bLIMIT\s+((([0-9]+)\s*,\s*)?([0-9]+)(\s+OFFSET\s+([0-9]+))?)/i';
964 if ( preg_match( $pattern, $sql, $matches ) ) {
965 $row_count = $matches[4];
966 $offset = $matches[3] ?
: $matches[6] ?
: false;
968 // strip the matching LIMIT clause out
969 $sql = str_replace( $matches[0], '', $sql );
971 return $this->limitResult( $sql, $row_count, $offset );
978 * @return string Wikitext of a link to the server software's web site
980 public function getSoftwareLink() {
981 return "[{{int:version-db-mssql-url}} MS SQL Server]";
985 * @return string Version information from the database
987 public function getServerVersion() {
988 $server_info = sqlsrv_server_info( $this->conn
);
989 $version = $server_info['SQLServerVersion'] ??
'Error';
995 * @param string $table
996 * @param string $fname
999 public function tableExists( $table, $fname = __METHOD__
) {
1000 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1002 if ( $db !== false ) {
1004 $this->queryLogger
->error( "Attempting to call tableExists on a remote table" );
1008 if ( $schema === false ) {
1009 $schema = $this->dbSchema();
1012 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.TABLES
1013 WHERE TABLE_TYPE = 'BASE TABLE'
1014 AND TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table'" );
1016 if ( $res->numRows() ) {
1024 * Query whether a given column exists in the mediawiki schema
1025 * @param string $table
1026 * @param string $field
1027 * @param string $fname
1030 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1031 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1033 if ( $db !== false ) {
1035 $this->queryLogger
->error( "Attempting to call fieldExists on a remote table" );
1039 $res = $this->query( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
1040 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1042 if ( $res->numRows() ) {
1049 public function fieldInfo( $table, $field ) {
1050 list( $db, $schema, $table ) = $this->tableName( $table, 'split' );
1052 if ( $db !== false ) {
1054 $this->queryLogger
->error( "Attempting to call fieldInfo on a remote table" );
1058 $res = $this->query( "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
1059 WHERE TABLE_SCHEMA = '$schema' AND TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
1061 $meta = $res->fetchRow();
1063 return new MssqlField( $meta );
1069 protected function doSavepoint( $identifier, $fname ) {
1070 $this->query( 'SAVE TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1073 protected function doReleaseSavepoint( $identifier, $fname ) {
1074 // Not supported. Also not really needed, a new doSavepoint() for the
1075 // same identifier will overwrite the old.
1078 protected function doRollbackToSavepoint( $identifier, $fname ) {
1079 $this->query( 'ROLLBACK TRANSACTION ' . $this->addIdentifierQuotes( $identifier ), $fname );
1083 * Begin a transaction, committing any previously open transaction
1084 * @param string $fname
1086 protected function doBegin( $fname = __METHOD__
) {
1087 sqlsrv_begin_transaction( $this->conn
);
1088 $this->trxLevel
= 1;
1093 * @param string $fname
1095 protected function doCommit( $fname = __METHOD__
) {
1096 sqlsrv_commit( $this->conn
);
1097 $this->trxLevel
= 0;
1101 * Rollback a transaction.
1102 * No-op on non-transactional databases.
1103 * @param string $fname
1105 protected function doRollback( $fname = __METHOD__
) {
1106 sqlsrv_rollback( $this->conn
);
1107 $this->trxLevel
= 0;
1114 public function strencode( $s ) {
1115 // Should not be called by us
1116 return str_replace( "'", "''", $s );
1120 * @param string|int|null|bool|Blob $s
1121 * @return string|int
1123 public function addQuotes( $s ) {
1124 if ( $s instanceof MssqlBlob
) {
1126 } elseif ( $s instanceof Blob
) {
1127 // this shouldn't really ever be called, but it's here if needed
1128 // (and will quite possibly make the SQL error out)
1129 $blob = new MssqlBlob( $s->fetch() );
1130 return $blob->fetch();
1132 if ( is_bool( $s ) ) {
1135 return parent
::addQuotes( $s );
1143 public function addIdentifierQuotes( $s ) {
1144 // http://msdn.microsoft.com/en-us/library/aa223962.aspx
1145 return '[' . $s . ']';
1149 * @param string $name
1152 public function isQuotedIdentifier( $name ) {
1153 return strlen( $name ) && $name[0] == '[' && substr( $name, -1, 1 ) == ']';
1157 * MS SQL supports more pattern operators than other databases (ex: [,],^)
1160 * @param string $escapeChar
1163 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
1164 return str_replace( [ $escapeChar, '%', '_', '[', ']', '^' ],
1165 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_",
1166 "{$escapeChar}[", "{$escapeChar}]", "{$escapeChar}^" ],
1170 protected function doSelectDomain( DatabaseDomain
$domain ) {
1171 $encDatabase = $this->addIdentifierQuotes( $domain->getDatabase() );
1172 $this->query( "USE $encDatabase" );
1173 // Update that domain fields on success (no exception thrown)
1174 $this->currentDomain
= $domain;
1180 * @param array $options An associative array of options to be turned into
1181 * an SQL query, valid keys are listed in the function.
1184 public function makeSelectOptions( $options ) {
1189 foreach ( $options as $key => $option ) {
1190 if ( is_numeric( $key ) ) {
1191 $noKeyOptions[$option] = true;
1195 $tailOpts .= $this->makeGroupByWithHaving( $options );
1197 $tailOpts .= $this->makeOrderBy( $options );
1199 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1200 $startOpts .= 'DISTINCT';
1203 if ( isset( $noKeyOptions['FOR XML'] ) ) {
1204 // used in group concat field emulation
1205 $tailOpts .= " FOR XML PATH('')";
1208 // we want this to be compatible with the output of parent::makeSelectOptions()
1209 return [ $startOpts, '', $tailOpts, '', '' ];
1212 public function getType() {
1217 * @param array $stringList
1220 public function buildConcat( $stringList ) {
1221 return implode( ' + ', $stringList );
1225 * Build a GROUP_CONCAT or equivalent statement for a query.
1226 * MS SQL doesn't have GROUP_CONCAT so we emulate it with other stuff (and boy is it nasty)
1228 * This is useful for combining a field for several rows into a single string.
1229 * NULL values will not appear in the output, duplicated values will appear,
1230 * and the resulting delimiter-separated values have no defined sort order.
1231 * Code using the results may need to use the PHP unique() or sort() methods.
1233 * @param string $delim Glue to bind the results together
1234 * @param string|array $table Table name
1235 * @param string $field Field name
1236 * @param string|array $conds Conditions
1237 * @param string|array $join_conds Join conditions
1238 * @return string SQL text
1241 public function buildGroupConcatField( $delim, $table, $field, $conds = '',
1244 $gcsq = 'gcsq_' . $this->subqueryId
;
1245 $this->subqueryId++
;
1247 $delimLen = strlen( $delim );
1248 $fld = "{$field} + {$this->addQuotes( $delim )}";
1249 $sql = "(SELECT LEFT({$field}, LEN({$field}) - {$delimLen}) FROM ("
1250 . $this->selectSQLText( $table, $fld, $conds, null, [ 'FOR XML' ], $join_conds )
1251 . ") {$gcsq} ({$field}))";
1256 public function buildSubstring( $input, $startPosition, $length = null ) {
1257 $this->assertBuildSubstringParams( $startPosition, $length );
1258 if ( $length === null ) {
1260 * MSSQL doesn't allow an empty length parameter, so when we don't want to limit the
1261 * length returned use the default maximum size of text.
1262 * @see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-textsize-transact-sql
1264 $length = 2147483647;
1266 return 'SUBSTRING(' . implode( ',', [ $input, $startPosition, $length ] ) . ')';
1270 * Returns an associative array for fields that are of type varbinary, binary, or image
1271 * $table can be either a raw table name or passed through tableName() first
1272 * @param string $table
1275 private function getBinaryColumns( $table ) {
1276 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1277 $tableRaw = array_pop( $tableRawArr );
1279 if ( $this->binaryColumnCache
=== null ) {
1280 $this->populateColumnCaches();
1283 return $this->binaryColumnCache
[$tableRaw] ??
[];
1287 * @param string $table
1290 private function getBitColumns( $table ) {
1291 $tableRawArr = explode( '.', preg_replace( '#\[([^\]]*)\]#', '$1', $table ) );
1292 $tableRaw = array_pop( $tableRawArr );
1294 if ( $this->bitColumnCache
=== null ) {
1295 $this->populateColumnCaches();
1298 return $this->bitColumnCache
[$tableRaw] ??
[];
1301 private function populateColumnCaches() {
1302 $res = $this->select( 'INFORMATION_SCHEMA.COLUMNS', '*',
1304 'TABLE_CATALOG' => $this->getDBname(),
1305 'TABLE_SCHEMA' => $this->dbSchema(),
1306 'DATA_TYPE' => [ 'varbinary', 'binary', 'image', 'bit' ]
1309 $this->binaryColumnCache
= [];
1310 $this->bitColumnCache
= [];
1311 foreach ( $res as $row ) {
1312 if ( $row->DATA_TYPE
== 'bit' ) {
1313 $this->bitColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1315 $this->binaryColumnCache
[$row->TABLE_NAME
][$row->COLUMN_NAME
] = $row;
1321 * @param string $name
1322 * @param string $format
1325 function tableName( $name, $format = 'quoted' ) {
1326 # Replace reserved words with better ones
1329 return $this->realTableName( 'mwuser', $format );
1331 return $this->realTableName( $name, $format );
1336 * call this instead of tableName() in the updater when renaming tables
1337 * @param string $name
1338 * @param string $format One of quoted, raw, or split
1341 function realTableName( $name, $format = 'quoted' ) {
1342 $table = parent
::tableName( $name, $format );
1343 if ( $format == 'split' ) {
1344 // Used internally, we want the schema split off from the table name and returned
1345 // as a list with 3 elements (database, schema, table)
1346 $table = explode( '.', $table );
1347 while ( count( $table ) < 3 ) {
1348 array_unshift( $table, false );
1356 * @param string $tableName
1357 * @param string $fName
1358 * @return bool|ResultWrapper
1361 public function dropTable( $tableName, $fName = __METHOD__
) {
1362 if ( !$this->tableExists( $tableName, $fName ) ) {
1366 // parent function incorrectly appends CASCADE, which we don't want
1367 $sql = "DROP TABLE " . $this->tableName( $tableName );
1369 return $this->query( $sql, $fName );
1373 * Called in the installer and updater.
1374 * Probably doesn't need to be called anywhere else in the codebase.
1375 * @param bool|null $value
1378 public function prepareStatements( $value = null ) {
1379 $old = $this->prepareStatements
;
1380 if ( $value !== null ) {
1381 $this->prepareStatements
= $value;
1388 * Called in the installer and updater.
1389 * Probably doesn't need to be called anywhere else in the codebase.
1390 * @param bool|null $value
1393 public function scrollableCursor( $value = null ) {
1394 $old = $this->scrollableCursor
;
1395 if ( $value !== null ) {
1396 $this->scrollableCursor
= $value;
1402 public function buildStringCast( $field ) {
1403 return "CAST( $field AS NVARCHAR )";
1409 * @deprecated since 1.29
1411 class_alias( DatabaseMssql
::class, 'DatabaseMssql' );